package com.taokatao.cardmee.common.widget;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;

import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;


public class RefreshHeader extends LinearLayout implements PtrUIHandler {
    private TextView tState;
    private ImageView iState, iLoad;

    public RefreshHeader(Context context) {
        this(context, null);
    }

    public RefreshHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_refresh_header, this);
        tState = (TextView) findViewById(R.id.t_state);
        iState = (ImageView) findViewById(R.id.i_state);
        iLoad = (ImageView) findViewById(R.id.i_load);
    }

    @Override
    public void onUIReset(PtrFrameLayout frame) {
        Utils.logd("RefreshHeader onUIReset");

        ((AnimationDrawable) iLoad.getBackground()).stop();
        iLoad.setVisibility(View.GONE);

        tState.setText("下拉可以刷新");
        iState.setVisibility(View.VISIBLE);
        iState.setImageResource(R.mipmap.refresh_down);
    }

    @Override
    public void onUIRefreshPrepare(PtrFrameLayout frame) {
        Utils.logd("RefreshHeader onUIRefreshPrepare");
    }

    @Override
    public void onUIRefreshBegin(PtrFrameLayout frame) {
        Utils.logd("RefreshHeader onUIRefreshBegin");
        iState.setVisibility(View.INVISIBLE);
        iLoad.setVisibility(View.VISIBLE);
        ((AnimationDrawable) iLoad.getBackground()).start();
        tState.setText("正在刷新数据");
    }

    @Override
    public void onUIRefreshComplete(PtrFrameLayout frame) {
        Utils.logd("RefreshHeader onUIRefreshComplete");
    }

    @Override
    public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
        // Utils.logd("RefreshHeader onUIPositionChange isUnderTouch %b # status %d", isUnderTouch, status);
        if (isUnderTouch) {
            if (ptrIndicator.getCurrentPercent() > ptrIndicator.getRatioOfHeaderToHeightRefresh()) {
                tState.setText("松开立即刷新");
                iState.setImageResource(R.mipmap.refresh_release);
            } else {
                tState.setText("下拉可以刷新");
                iState.setImageResource(R.mipmap.refresh_down);
            }
        }
    }
}
